<template>
  <div class="singer">
    <list-view :data="singer" @select="selectSinger"></list-view>
    <router-view></router-view>
  </div>
</template>

<script type="text/ecmascript-6">
import { ERR_OK } from "api/config";
import { getSingerList } from "api/singer";
import Singer from "common/js/singer";
import ListView from "base/listview";
import { mapMutations } from 'vuex'

const HOT_NAME = "热门";
const HOT_SINGER_LEN = 10;

export default {
  name: "Singer",
  data() {
    return {
      singer: []
    };
  },
  components: {
    ListView
  },

  created() {
    this._getSingerList();
  },

  methods: {
    selectSinger(singer) {
      this.setSinger(singer)
      this.$router.push({
        path: `/singer/${singer.id}`
      })
    },
    _getSingerList() {
      getSingerList().then(res => {
        if (res.code === ERR_OK) {
          this.singer = this._normalizeSinger(res.data.list);
        }
      });
    },
    // 处理数据结构
    _normalizeSinger(list) {
      let map = {
        hot: {
          title: HOT_NAME,
          items: []
        }
      };
      list.forEach((item, index) => {
        // 热门数据
        if (index < HOT_SINGER_LEN) {
          map.hot.items.push(
            new Singer({
              id: item.Fsinger_mid,
              name: item.Fsinger_name
            })
          );
        }
        // 其它数据
        const key = item.Findex;
        if (!map[key]) {
          map[key] = {
            title: key,
            items: []
          };
        }
        map[key].items.push(
          new Singer({
            id: item.Fsinger_mid,
            name: item.Fsinger_name
          })
        );
      });

      // 处理数据
      let hot = [];
      let ret = [];
      for (let key in map) {
        let val = map[key];
        if (map[key].title.match(/[a-zA-Z]/)) {
          ret.push(map[key]);
        } else if (map[key].title === HOT_NAME) {
          hot.push(map[key]);
        }
      }
      ret.sort((a, b) => {
        return a.title.charCodeAt(0) - b.title.charCodeAt(0);
      });

      return hot.concat(ret);
    },
    ...mapMutations({
      setSinger: 'SET_SINGER'
    })
  }
};
</script>

<style lang="stylus" scoped>
.singer {
  position: fixed;
  top: 88px;
  bottom: 0;
  width: 100%;
}
</style>
